package calculator;

import java.lang.reflect.InvocationTargetException;

public class OperationResolver {

	private CalculatorProxy calculatorProxy;
	private ExpressionHandler expressionHandler;

	public OperationResolver(CalculatorProxy calculatorProxy,
			ExpressionHandler expressionHandler) {
		super();
		this.calculatorProxy = calculatorProxy;
		this.expressionHandler = expressionHandler;
	}


	public String[] resolve(String... expression) throws NumberFormatException,
			NoSuchMethodException, IllegalAccessException,
			InvocationTargetException, OverflowException {
		int higestPriorityOp = expressionHandler.highestPriorityOp(expression) ;
		String operation = expression[higestPriorityOp];
		String operation_name = null;
		if ("+".equals(operation)) {
			operation_name = "add";
		} else if ("*".equals(operation)) {
			operation_name = "times";
		}
		Integer result = calculatorProxy.binaryOperation(operation_name,
				Integer.parseInt(expression[higestPriorityOp - 1]),
				Integer.parseInt(expression[higestPriorityOp + 1]));
		String [] simplified = new String [expression.length - 2];
		
		for (int i = 0; i < higestPriorityOp - 1; i++) {
			simplified [i] = expression[i];
		}
		simplified[higestPriorityOp - 1] = result.toString();
		for (int i = higestPriorityOp + 2; i < expression.length; i++) {
			simplified [i - 2] = expression[i];
		}
		return  simplified;
	}

}
